<template>
    <div class="filter">
        <!-- <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                style="width: 145px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div> -->

        <div class="filter-item">
            <label for="">模板名称：</label>
            <el-input
                v-model="searchForm.templateName"
                style="width: 145px"
            />
        </div>
        <div class="filter-item">
            <label for="">模板类型：</label>
            <el-select
                v-model="searchForm.templateType"
                class="m-2"
                style="width: 145px"
            >
                <el-option
                    v-for="item in templateTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <el-button
                size="default"
                type="primary"
                @click="search"
            >查询</el-button>
            <el-button
                size="default"
                @click="reset"
            >重置</el-button>
        </div>
    </div>
    <div class="filter">
        <div class="filter-item">
            <el-button
                type="primary"
                @click="handleClick('add')"
            >新增</el-button>
        </div>
    </div>
    <el-table
        :data="tableData"
        style="width: 100%"
        id="inspectionTask"
    >
        <el-table-column
            type="index"
            label="序号"
            width="55"
        />
        <el-table-column
            prop="templateName"
            label="模版名称"
        />
        <el-table-column
            prop="personnelNum"
            label="适用人数"
        />
        <el-table-column
            prop="templateType"
            label="适用人数"
        >
            <template #default="scope">
                {{ scope.row.templateType == 1 ? '平台模板' : '个人模板' }}
            </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="160"
        >
            <template #default="scope">
                <el-button
                    type="primary"
                    size="small"
                    :icon="View"
                    @click="handleClick('detail', scope.row)"
                >
                </el-button>
                <el-button
                    type="primary"
                    size="small"
                    :icon="Edit"
                    @click="handleClick('edit', scope.row)"
                >
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click="handleDelete(scope.row)"
                ></el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog
        ref="templateName"
        v-model="templateNameVisible"
        :title="templateTitle"
        width="900"
    >
        <div class="dialogContent">
            <el-form
                ref="templateFormRef"
                :model="templateForm"
                label-width="100px"
                class="demo-ruleForm"
                :inline="true"
                :disabled="templateType == 'detail'"
            >
                <div class="dialogModel">
                    <el-row :span="24">
                        <el-col :span="8">
                            <el-form-item
                                label="模板名称："
                                prop="templateName"
                                style="width: 100%;"
                            >
                                <el-input
                                    v-model="templateForm.templateName"
                                    placeholder="请输入"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="模板类型："
                                prop="templateType"
                                style="width: 100%;"
                            >
                                <el-select
                                    v-model="templateForm.templateType"
                                    class="m-2"
                                >
                                    <el-option
                                        v-for="item in templateTypeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="适用人数："
                                prop="personnelNum"
                                style="width: 100%;"
                            >
                                <el-select
                                    v-model="templateForm.personnelNum"
                                    class="m-2"
                                >
                                    <el-option
                                        v-for="item in personnelNumList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-show="templateForm.templateType == 2">
                        <el-col :span="24">
                            <el-form-item
                                label="描述："
                                prop="commets"
                                style="width: 100%;"
                            >
                                <el-input
                                    :rows="2"
                                    type="textarea"
                                    v-model="templateForm.commets"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="templateNameVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="templateNameConfirm()"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        ref="templateContent"
        v-model="templateContentVisible"
        :title="templateTitle"
        width="1100"
    >
        <div class="dialogContent">
            <el-form
                ref="templateFormRef"
                :model="templateForm"
                label-width="100px"
                class="demo-ruleForm"
                :inline="true"
                :disabled="templateType == 'detail'"
            >
                <div style="width: 100%;">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                label="模板名称："
                                prop="templateName"
                                style="width: 100%;"
                            >
                                <el-input
                                    v-model="templateForm.templateName"
                                    placeholder="请输入"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="模板类型："
                                prop="templateType"
                                style="width: 100%;"
                            >
                                <el-select
                                    v-model="templateForm.templateType"
                                    class="m-2"
                                    disabled
                                >
                                    <el-option
                                        v-for="item in templateTypeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="适用人数："
                                prop="personnelNum"
                                style="width: 100%;"
                            >
                                <el-select
                                    v-model="templateForm.personnelNum"
                                    class="m-2"
                                    disabled
                                >
                                    <el-option
                                        v-for="item in personnelNumList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-show="templateForm.templateType == 2">
                        <el-col :span="24">
                            <el-form-item
                                label="描述："
                                prop="commets"
                                style="width: 100%;"
                            >
                                <el-input
                                    :rows="2"
                                    type="textarea"
                                    v-model="templateForm.commets"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-scrollbar height="440px">
                    <div class="taskContent">
                        <div
                            class="dialogModel"
                            v-for="(item, index) in templateForm.taskSort"
                            :key="index"
                        >
                            <div class="modelTitle">
                                <div>任务排序{{ index + 1 }}</div>
                                <div
                                    class="operateIcon"
                                    v-show="templateType != 'detail'"
                                >
                                    <img
                                        src="../../../../assets/images/plus.png"
                                        alt=""
                                        @click="addTaskItem(index)"
                                    >
                                </div>
                            </div>

                            <div
                                class="taskList"
                                id="taskList"
                            >
                                <el-scrollbar max-height="380px">
                                    <div
                                        class="taskItem"
                                        v-for="(m, n) in item.taskItemList"
                                        :key="n"
                                    >
                                        <div
                                            class="delelteItem"
                                            @click="deleteTaskItem(index, n)"
                                            v-show="item.taskItemList.length > 1 && templateType != 'detail'"
                                        >
                                            <el-icon
                                                class="elIcon"
                                                :size="12"
                                                color="#fff"
                                            >
                                                <Delete />
                                            </el-icon>
                                        </div>
                                        <div class="taskItemName">
                                            <div>

                                                <el-select
                                                    v-model="m.title"
                                                    class="m-2"
                                                    style="width: 270px;margin-right: 10px;"
                                                    @change="(val) => taskItemDetails(val, index, n)"
                                                >
                                                    <el-option
                                                        v-for="item in taskItemDictList"
                                                        :key="item.title"
                                                        :label="item.title"
                                                        :value="item.title"
                                                    />
                                                </el-select>
                                                <!-- <el-input
                                                    v-model="m.sort"
                                                    placeholder="排序"
                                                    style="width: 80px;"
                                                /> -->
                                            </div>
                                        </div>
                                        <div class="taskItemTable">
                                            <el-table
                                                :data="m.itemTableList"
                                                style="width: 100%"
                                                id="inspectionTask"
                                                v-show="m.itemTableList.length > 0"
                                            >
                                                <el-table-column
                                                    prop="title"
                                                    label="步骤"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="decompositionStepValue"
                                                    label="步骤分解"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="startTime"
                                                    label="推荐时间"
                                                    width="180"
                                                >
                                                    <template #default="scope">
                                                        <el-time-picker
                                                            v-model="scope.row.planStartTime"
                                                            style="width: 80px;margin-right: 2px;"
                                                            format="HH:mm"
                                                            value-format="HH:mm"
                                                        />
                                                        <el-time-picker
                                                            v-model="scope.row.planEndTime"
                                                            style="width: 80px;"
                                                            format="HH:mm"
                                                            value-format="HH:mm"
                                                        />
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                </el-scrollbar>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="templateContentVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="templateContentConfirm()"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
// utils
import Storage from "@/utils/storage.js";
import {
    Delete,
    Edit,
    View
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
// ref
let searchForm = ref({
    depId: '',
    templateName: '',
    personnelNum: '',

});
const templateNameVisible = ref(false)
const templateContentVisible = ref(false)
const templateType = ref('add')
const templateTitle = ref('新增')
const templateForm = ref({
    templateName: '',
    templateType: '',
    personnelNum: 1,
    commets: '',
    taskSort: [],
})
const taskItemDictList = ref([])
// api
import taskHttp from "@/https/task.js";
const localTypeUnit = ref();
localTypeUnit.value = Storage.localGet("depId")
console.log(localTypeUnit.value, 'localTypeUnit.value ')
// searchForm.value.depId = Number(localTypeUnit.value) == 1 ? 2 : Number(localTypeUnit.value)
const tableData = ref([]);
// dict
// dict
const depIdList = ref([
    { label: "星沙厂", value: 2 },
    { label: "城西厂", value: 3 },
    { label: "城北厂", value: 4 },
    { label: "城南厂", value: 5 },
    { label: "城东厂", value: 6 },
]);
const templateTypeList = ref([
    { label: "全部", value: "" },
    { label: "平台模板", value: 1 },
    { label: "个人模板", value: 2 },
]);
const personnelNumList = ref([
    { label: "全部", value: "" },
    { label: "1人", value: 1 },
    { label: "2人", value: 2 },
    { label: "3人", value: 3 },
]);
// methods
// 重置
const reset = async () => {
    searchForm.value.title = ''
    searchForm.value.taskCategory = 1
    search()
}
// 查询
const search = async () => {
    const res = await taskHttp.queryTaskTemplateList(searchForm.value)
    tableData.value = res.data.data.personn1List.concat(res.data.data.personn2List.concat(res.data.data.personn3List))
}
const handleClick = (type, row) => {
    templateType.value = type
    taskItemDictList.value.forEach((m, n) => {
        m.itemTableList.forEach((p, q) => {
            p.planStartTime = ''
            p.planEndTime = ''
        })
    })
    if (type == 'add') {
        templateNameVisible.value = true
        templateForm.value.templateName = ''
        templateForm.value.personnelNum = 1
        templateForm.value.taskSort = []
        templateTitle.value = '新增'
    } else if (type == 'detail') {
        templateContentVisible.value = true
        templateTitle.value = '详情'
        getTemplateContent(row)
    } else if (type == 'edit') {
        templateContentVisible.value = true
        templateTitle.value = '编辑'
        getTemplateContent(row)
    }
}
const handleDelete = async (row) => {
    ElMessageBox.confirm(`确认删除模板【${row.templateName}】吗？`, `删除`, {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        taskHttp.delTaskTemplate(row).then((res) => {
            if (res.data.code === 200) {
                search();
            }
        });
    });
}
const getTemplateContent = (row) => {
    templateForm.value.id = row.id
    templateForm.value.templateName = row.templateName
    templateForm.value.personnelNum = row.personnelNum
    templateForm.value.templateType = row.templateType
    templateForm.value.taskSort = []
    for (let i = 0; i < row.personnelNum; i++) {
        templateForm.value.taskSort.push({
            taskItemList: []
        })
        let rowIndexName = i == 0 ? '' : i + 1
        console.log(`requiredIdsItems${rowIndexName}`, row[`requiredIdsItems${rowIndexName}`], row[`taskTemplateTimesetVos${rowIndexName}`], 'rowIndexName')
        let requiredIdsItemsList = row[`requiredIdsItems${rowIndexName}`].split(',')
        console.log(taskItemDictList, 'taskItemDictList')
        let taskTemplateTimesetVosList = JSON.parse(row[`taskTemplateTimesetVos${rowIndexName}`])
        requiredIdsItemsList.forEach(item => {
            taskItemDictList.value.forEach((m, n) => {
                if (item == m.id) {
                    m.itemTableList.forEach((p, q) => {
                        taskTemplateTimesetVosList.forEach((k, l) => {
                            if (p.id == k.id) {
                                p.planStartTime = JSON.parse(JSON.stringify(k.planStartTime))
                                p.planEndTime = JSON.parse(JSON.stringify(k.planEndTime))
                            }
                        })
                    })
                    console.log(m, 'mmmmmmm')
                    templateForm.value.taskSort[i].taskItemList.push({ ...m })
                }
            })
        })
    }
    console.log(templateForm.value, 'templateForm.value')
}
const templateNameConfirm = () => {
    templateForm.value.taskSort = []
    templateNameVisible.value = false
    templateContentVisible.value = true
    if (templateType.value == 'add') {
        for (let i = 0; i < templateForm.value.personnelNum; i++) {
            templateForm.value.taskSort.push({
                taskItemList: [{
                    name: '',
                    sort: 1,
                    itemTableList: []
                }]
            })
        }
        console.log(templateForm.value, 'templateForm.value')
    }

}
// 查询
const searchTask = async () => {
    const res = await taskHttp.queryTaskList(searchForm.value)
    console.log(res.data.data, 'res')
    const newDataList = res.data.data.filter((item) => {
        return item.isDeleted == 0
    })
    let taskItemListArr = []
    newDataList.forEach(item => {
        let taskItem = {
            title: '',
            id: '',
            itemTableList: []
        }
        taskItem.id = item.id
        taskItem.title = item.title
        if (item.childrens && item.childrens.length > 0) {
            item.childrens.forEach((m, n) => {
                if (m.childrens && m.childrens.length > 0) {
                    m.childrens.forEach((p, q) => {
                        taskItem.itemTableList.push({
                            id: p.id,
                            title: m.title,
                            decompositionStepValue: p.title,
                            planStartTime: '',
                            planEndTime: ''
                        })
                    })
                } else {
                    taskItem.itemTableList.push({
                        id: m.id,
                        title: m.title,
                        decompositionStepValue: '',
                        planStartTime: '',
                        planEndTime: ''
                    })
                }
            })
        }
        taskItemListArr.push(taskItem)
    })
    taskItemDictList.value = taskItemListArr
    console.log(taskItemDictList.value, 'taskItemDictList.value')
}
const taskItemDetails = (val, index, n) => {
    for (let i = 0; i < templateForm.value.personnelNum; i++) {
        templateForm.value.taskSort.forEach(item => {
            item.taskItemList.forEach(m => {
                m.itemTableList.forEach(p => {
                    p.planStartTime = ''
                    p.planEndTime = ''
                })
            })
        })
    }
    taskItemDictList.value.forEach(item => {
        if (item.title == val) {
            console.log(item, 'val')
            templateForm.value.taskSort[index].taskItemList[n].itemTableList = JSON.parse(JSON.stringify(item.itemTableList))
            templateForm.value.taskSort[index].taskItemList[n].id = item.id
            templateForm.value.taskSort[index].taskItemList[n].title = item.title
        }
    })
}
// 新增任务项
const addTaskItem = (index) => {
    templateForm.value.taskSort[index].taskItemList.push({
        name: '',
        sort: '',
        id: '',
        itemTableList: [{
            startTime: '',
            endTime: '',
            step: '',
            decomposeSteps: []
        }]
    })
}
// 删除任务项
const deleteTaskItem = (index, n) => {
    templateForm.value.taskSort[index].taskItemList.splice(n, 1)
}
const taskList = ref([])
// 查询
const taskListFn = async () => {
    const res = await taskHttp.queryTaskList(searchForm.value)
    taskList.value = res.data.data
}
const templateContentConfirm = async () => {
    console.log(templateForm.value, 'templateForm')
    let params = {
        depId: searchForm.value.depId,
        id: templateForm.value.id,
        templateName: templateForm.value.templateName,
        templateType: templateForm.value.templateType,
        personnelNum: templateForm.value.personnelNum,
        commets: templateForm.value.commets,
        requiredTitlesItems: '',
        taskTemplateTimesetVos: '',
        requiredIdsItems: '',
    }
    if (templateForm.value.templateType == 2) {
        params.userId = Storage.localGet("userId")
    }
    for (let i = 0; i < templateForm.value.personnelNum; i++) {
        let requiredTitlesItemsList = []
        let requiredIdsItemsList = []
        let taskTemplateTimesetVosList = []
        console.log(templateForm.value.taskSort[i], 'templateForm.value.taskSort')
        templateForm.value.taskSort[i].taskItemList.forEach((item, index) => {
            requiredIdsItemsList.push(item.id)
            requiredTitlesItemsList.push(item.title)
            templateForm.value.taskSort[i].taskItemList[index].itemTableList
                .forEach((p, q) => {
                    taskTemplateTimesetVosList.push({
                        id: p.id,
                        planStartTime: p.planStartTime,
                        planEndTime: p.planEndTime,
                        title: p.decompositionStepValue,
                    })
                })
        })
        console.log(taskTemplateTimesetVosList, 'taskTemplateTimesetVosList')
        let requiredTitlesItemsListSort = []
        let requiredIdsItemsListSort = []
        taskList.value.forEach(item => {
            requiredIdsItemsList.forEach(k => {
                if (item.id == k) {
                    requiredIdsItemsListSort.push(k)
                }
            })
        })
        taskList.value.forEach(item => {
            requiredTitlesItemsList.forEach(k => {
                if (item.title == k) {
                    requiredTitlesItemsListSort.push(k)
                }
            })
        })
        console.log(requiredTitlesItemsListSort, requiredIdsItemsListSort, 'item')
        if (i == 0) {
            params[`requiredIdsItems`] = requiredIdsItemsListSort.join(',')
            params[`requiredTitlesItems`] = requiredTitlesItemsListSort.join(',')
            params[`taskTemplateTimesetVos`] = JSON.stringify(taskTemplateTimesetVosList)
        } else {
            params[`requiredIdsItems${i + 1}`] = requiredIdsItemsListSort.join(',')
            params[`requiredTitlesItems${i + 1}`] = requiredTitlesItemsListSort.join(',')
            params[`taskTemplateTimesetVos${i + 1}`] = JSON.stringify(taskTemplateTimesetVosList)
        }
    }
    console.log(params, 'params')
    // return
    if (templateType.value == 'add') {
        const res = await taskHttp.addTaskTemplate(params)
        if (res.data.code == 200) {
            templateContentVisible.value = false
            search()
            ElMessage({
                type: "success",
                message: '新增成功'
            });
        }
    } else {
        const res = await taskHttp.updateTaskTemplate(params)
        if (res.data.code == 200) {
            templateContentVisible.value = false
            search()
            ElMessage({
                type: "success",
                message: '修改成功'
            });
        }
    }
}

onMounted(() => {
    search()
    searchTask()
    taskListFn()
})
</script>
<style lang="less" scoped>
.dialogModelBox {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .dialogModel {
        flex: 1;
    }
}
.taskContent {
    display: flex;
    flex-direction: row;
    width: fit-content;
}
.dialogContent {
    .dialogModel {
        padding-right: 20px;
        flex: 1;
        min-width: 500px;
        .modelTitle {
            font-size: 16px;
            line-height: 18px;
            height: 18px;
            padding-left: 10px;
            border-left: 4px solid #58be3f;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            .operateIcon {
                margin-left: 10px;
                img {
                    width: 18px;
                    height: 18px;
                    margin: 0 2px;
                    cursor: pointer;
                }
            }
        }
    }
}
.operateIcon {
    display: flex;
    flex-direction: row;
    align-items: center;
}
.el-col-content {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    padding-bottom: 20px;
    .el-col-content-input {
        margin-right: 10px;
    }
}
.el-col-content-mr {
    margin-right: 10px;
    cursor: pointer;
}
.calculationFormula {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: 12px;
    .calculationFormulaContent {
        flex: 1;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        flex-wrap: wrap;
        .calculationFormulaContentItem {
            position: relative;
            .delelteItem {
                position: absolute;
                right: 1px;
                top: -3px;
                z-index: 1000;
                background: #f56c6c;
                border-radius: 4px;
                padding: 2px 2px 0px;
            }
        }
    }
}
.taskList {
    .taskItem {
        margin-bottom: 10px;
        position: relative;
        .taskItemName {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin-bottom: 4px;
        }
        .taskItemTable {
            .recommendTime {
                display: flex;
                flex-direction: row;
                justify-content: flex-start;
                align-items: center;
            }
        }
        .delelteItem {
            position: absolute;
            right: 0px;
            top: 0px;
            z-index: 1000;
            background: #f56c6c;
            border-radius: 4px;
            padding: 2px 2px 0px;
            cursor: pointer;
        }
    }
}
.operateIcon {
    img {
        width: 18px;
        height: 18px;
        margin: 0 2px;
        cursor: pointer;
    }
}
:deep #taskList .el-input__prefix-inner {
    display: none !important;
}
:deep #taskList .el-table .cell {
    padding: 0 4px !important;
}
:deep #taskList .el-table .el-table__cell {
    padding: 2px 0 !important;
    font-weight: normal !important;
}
</style>